// Copyright (c) 2000

package com.phevos.common.dbpool;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * l�ӳؽӿڡ�
 */
public abstract class ConnectionPool
{

    protected BasicDataSource ds = null;

    /**
     * ��l�ӳ��еõ�һ������ݿ��l�ӡ�
     * 
     * @throw DBPoolException �����ܻ��һ��l��ʱ���׳�����⡣
     * @throw SQLException ���ܻ��һ��l�������������ݿ����ʧ�ܣ��׳�����⡣
     */
    public Connection getConnection() throws com.phevos.common.dbpool.exception.DBPoolException,
            SQLException
    {
        Connection conn = ds.getConnection();
        if (conn != null)
        {
            return conn;
        }
        else
        {
            throw new com.phevos.common.dbpool.exception.DBPoolException("pool busy");
        }
    }

    protected void initDataSource()
    {
        ds = new BasicDataSource();

        ds.setTestOnBorrow(true);
        ds.setTestOnReturn(true);
        ds.setTestWhileIdle(true);
        ds.setValidationQuery("select count(*) from dual");

        ds.setDriverClassName(PoolConfig.getInstance().getDriver());
        ds.setUsername(PoolConfig.getInstance().getUser());
        ds.setPassword(PoolConfig.getInstance().getPassword());
        ds.setUrl(PoolConfig.getInstance().getUrl());
        // ����l�ӳز���
        PoolSetting poolSetting = PoolConfig.getInstance().getPoolSetting(getPoolIdentifier());
        if (poolSetting != null)
        {
            ds.setMaxActive(poolSetting.getMaxActive());
            ds.setMaxIdle(poolSetting.getMaxIdle());
            ds.setMinIdle(poolSetting.getMinIdle());
            ds.setMaxWait(poolSetting.getMaxWait());
            ds.setTimeBetweenEvictionRunsMillis(poolSetting.getTimeBetweenEvictionRunsMillis());
            ds.setNumTestsPerEvictionRun(poolSetting.getNumTestsPerEvictionRun());
            ds.setMinEvictableIdleTimeMillis(poolSetting.getMinEvictableIdleTimeMillis());
        }
    }

    /**
     * ��һ��l�ӷŻ���ݿ�l�ӳء�
     * 
     * @param conn Ҫ�Ż�l�ӳص�һ��l�ӡ�
     * @throw SQLException ��ݿ����ʧ��ʱ���׳�����⡣ modify by zhaoch on
     *        20040615:���connΪnull,�����"l�ӳش������",�Ӷ���ܴ���l�ӳ����³�ʼ��
     */
    public void returnConnection(Connection conn) throws SQLException
    {
        if (conn != null)
        {
            conn.close();
        }
    }

    abstract String getPoolIdentifier();

}
